package cn.lhx.blog.plugin.flashPlayer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;

import org.xmappr.Xmappr;

public class PlayerHelper {
	public static void savePlayList(PlayList playList,String filePath){
		System.out.println("保存播放列表！");
		if(playList==null){
			throw new NullPointerException();
		}
		Xmappr xmappr=new Xmappr(PlayList.class);
		
		
		File file=new File(filePath);
		try {
			
			FileOutputStream fout=new FileOutputStream(file);
			OutputStreamWriter writer=new OutputStreamWriter(fout,"utf-8");
			String xmlHeader="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			writer.write(xmlHeader, 0, xmlHeader.getBytes().length);
			System.out.println(writer.getEncoding()+"Encodeing");
			xmappr.toXML(playList, writer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static PlayList loadPlayList(String filePath){
		System.out.println("读取播放列表！");
		File file=new File(filePath);
		
		Xmappr xmappr=new Xmappr(PlayList.class);
		try {
			FileInputStream fin=new FileInputStream(file);
			byte[] bufb=new byte[fin.available()];
			fin.read(bufb);
			StringReader reader=new StringReader(new String(bufb,"utf-8"));
			PlayList playList=(PlayList)xmappr.fromXML(reader);
//			为每首哥加个ID
			int id=0;
			for(Track track : playList.getTrackList().get(0).getTrack()) {
				   track.setId(id++);
			}
			return playList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
